package job

import (
	"context"
	"time"
	"strings"
	"strconv"
	"fmt"

	"night-school-api/pkg/redis"
	"night-school-api/database"
	"night-school-api/models"
	"night-school-api/utils"
)

// 定时任务队列
type JobQueue struct {
	redisClient *redis.Client
}

func NewJobQueue(rc *redis.Client) *JobQueue {
	return &JobQueue{redisClient: rc}
}

const CourseStartJobRedisKey = "course_start_queue"

// 添加定时任务
func (jq *JobQueue) CreateCourseStartJob(ctx context.Context, taskID string, expireAt time.Time) error {
	
	fmt.Printf("CreateCourseStartJob() taskID: %#v \n", taskID)
	return jq.redisClient.AddDelayTask(
		ctx,
		CourseStartJobRedisKey,
		taskID,
		expireAt,
	)
}

// 取消任务
func (jq *JobQueue) CancelCourseStartJob(ctx context.Context, taskID string) error {
	// 从队列删除任务
	return jq.redisClient.RemoveTask(
		ctx,
		CourseStartJobRedisKey,
		taskID,
	)
}

func HandleCourseStartJob(ctx context.Context, taskID string) error {
	
	var idStr string
	colonIndex := strings.Index(taskID, ":")
	if colonIndex != -1 && (colonIndex + 1) < len(taskID) {
		idStr = taskID[colonIndex+1:]
	} else {
		idStr = ""
	}
	id, err := strconv.Atoi(idStr)
	if err != nil {
		id = 0
	}

	if id <= 0 {
		return nil
	}

	fmt.Printf("处理开课提醒定时任务，课程id: %#v \n", id)
	
	db := database.DB

	var course models.Course
	db.Find(&course, id)
	if course.ID <= 0 || course.Status != models.AuditApproved {
		return nil
	}

	query := db.Model(&models.Enrollment{}).Where("course_id = ?", id).Where("status = ?", models.AuditApproved)

	var total int64
	var enrolls []models.EnrollmentRecord
	
	query.Count(&total)
	if total < 1 {
		return nil
	}

	startAtStr := course.StartAt.Format("2006-01-02 15:04")
	statuZh := "您报名的课程即将开始，请记得按时上课"


	size := 10
	page := 1
	for ((page - 1) * size) < int(total) {
		query.Preload("User").Limit(size).Offset((page - 1) * size).Find(&enrolls)
		page = page + 1
		
		fmt.Printf("课程 (id: %d) 需要发送开课提醒的用户共 %d 人\n", course.ID, total)

		for i := range(enrolls) {
			enroll := enrolls[i]
			// fmt.Printf("enroll: %#v \n", enrolls)

			if enroll.User.Openid == "" {
				continue
			}

			if enroll.ID > 0 && enroll.Status == models.AuditApproved && enroll.IsCourseStartSubscribed == 1 {

				fmt.Printf("发送开课提醒给（id：%d, %s), 课程id：%d \n", enroll.User.ID, enroll.User.Name, course.ID)

				err = utils.CourseStartSendMsg(ctx, course.ID, enroll.User.Openid, course.Name, course.TeacherName, startAtStr, statuZh)
				fmt.Printf("发送开课提醒结果 err: %#v \n", err)
			}
		}
	}
	return nil
}